<script setup lang="ts">
import gfm from '@bytemd/plugin-gfm'
import highlight from '@bytemd/plugin-highlight';
import gemoji from "@bytemd/plugin-gemoji";
import frontmatter from "@bytemd/plugin-frontmatter";
import {Editor, Viewer} from '@bytemd/vue-next'
import {ref} from "vue";
import {base_Hans, gfm_Hans} from '../../plugins/zh_Hans.js'
import './index.css'
import myAxios from "../../plugins/myAxios.ts";
import FlyTagSelect from "../../components/fly-tag-select.vue";
import {Message, Notification} from '@arco-design/web-vue';
import {router} from "../../router";


const value = ref('')
const title = ref('')
const tags = ref([])
const plugins = [
  gfm({
    locale: gfm_Hans
  }),
  gemoji(),
  frontmatter(),
  highlight(),
]

const handleChange = (v: string) => {
  value.value = v
}

const addTag = (tag: string) => {
  tags.value.push(tag)
  console.log(tags.value)
}
const removeTag = (tag: string) => {
  tags.value = tags.value.filter(t => t !== tag)
}

const savePost = () => {
  myAxios.post('/post/add', {
    title: title.value,
    content: value.value,
    tags: tags.value
  }).then(res => {
    if (res.code === 0) {
      Notification.success("发布成功!")
      router.back()
    } else if (res.code === 40100){
      Message.error("请先登录！")
      router.push('/login')
    } else {
      Message.error(res.message)
    }
  })
}
</script>

<template>
  <div id="edit-post">
    <header class="header">
      <a-input placeholder="请输入标题" size="large" v-model="title"/>
      <div class="add-tags">
        <a-popover trigger="click">
          <a-button>添加标签</a-button>
          <template #content>
            <fly-tag-select :data="tags" @add="addTag" @remove="removeTag"/>
          </template>
        </a-popover>
      </div>
      <a-button type="primary" @click="savePost">发布</a-button>
      <a-button type="primary" @click="$router.back">取消</a-button>
    </header>
    <Editor :value="value" :plugins="plugins" @change="handleChange" :locale="base_Hans" placeholder="写下你的想法吧！"/>
  </div>
</template>

<style scoped>
#edit-post {
  width: 100%;
  height: 100%;
}

.header {
  height: 100%;
  display: flex;
  justify-content: space-between;
}

.header :deep(.arco-input-wrapper) {
  width: 80%;
}

:deep(.bytemd) {
  height: 94vh;
  border: 0;
}
</style>